package com.hxut.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hxut.common.dto.SysMenuDto;
import com.hxut.common.lang.Result;
import com.hxut.entity.SysMenu;
import com.hxut.entity.SysRoleMenu;
import com.hxut.entity.SysUser;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author MR.S
 * @since 2022-06-21
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {

    /**
     * @param principal
     * @description: 当前用户的菜单和权限信息
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/11 19:34
     */
    @GetMapping("/nav")
    public Result nav(Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());

        //获取权限信息
        String authorityInfo = sysUserService.getAuthorityInfo(sysUser.getId());
        //ROLE_admin,ROLE_normal,sys:user:list.. 它的权限信息是字符串格式，这里要变成数组格式
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");

        //获取导航菜单信息
        List<SysMenuDto> navs = sysMenuService.getCurrentUserNav();

        return Result.success(MapUtil.builder()
                .put("authoritys", authorityInfoArray)
                .put("nav", navs)
                .map());
    }

    /**
     * @param id
     * @description: 编辑菜单
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/11 20:37
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAnyAuthority('sys:menu:list')")
    public Result info(@PathVariable(name = "id") Long id) {
        SysMenu menu = sysMenuService.getById(id);
        return Result.success(menu);
    }

    /**
     * @description: 查询所有菜单信息
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/11 20:55
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result list() {
        List<SysMenu> menus = sysMenuService.tree();
        return Result.success(menus);
    }

    /**
     * @param sysMenu
     * @description: 新增菜单信息
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/11 21:14
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result save(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setCreated(LocalDateTime.now());
        sysMenuService.save(sysMenu);
        return Result.success(sysMenu);
    }

    /**
     * @description:  更改菜单信息
     * @param sysMenu
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/11 21:41
    */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result update(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setUpdated(LocalDateTime.now());
        sysMenuService.updateById(sysMenu);

        //当菜单信息进行更改时,清空所有与菜单相关的缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.success(sysMenu);
    }
    /**
     * @description: 删除菜单信息
 * @param id
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 8:47
    */
    @Transactional
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result delete(@PathVariable(name = "id") Long id) {

        //如果有匹配数量不为0,那么说明该菜单有子菜单，无法删除，需要删除子菜单才能删除当前菜单
        int matcherCount = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if(matcherCount>0){
            return Result.fail("请先删除子菜单");
        }

        //删除当前菜单
        sysMenuService.removeById(id);

        //同步删除中间关联表
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id",id));

        //并且清除与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);

        return Result.success("删除当前菜单成功");
    }


}
